package cn.fl.collection.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.collection.constant.CollectionConstant;
import cn.fl.collection.service.IRskCltAuthRecordService;
import cn.fl.collection.service.IRskCltAuthService;
import cn.fl.collection.vo.RskCltAuthVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.risknew.condition.RskCommRecQueryCondition;
import cn.fl.risknew.constant.RiskConstant;
import cn.fl.risknew.dto.RskCommRecDTO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.vo.SysUlFilesRecVO;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @Description:    委外催收记录Controller
* @Author:         liurong
* @CreateDate:     2020/4/23 14:10
* @Version:        1.0
*/
@Controller
@RequestMapping("/clt/auth/record")
public class RskCltAuthRecordController {

    @Autowired
    private IRskCltAuthService rskCltAuthService;

    @Autowired
    private IRskCltAuthRecordService rskCltAuthRecordService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    /**
     * 跳转新增催收记录页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/showAddCltRcdPage.do", method = {RequestMethod.GET})
    public ModelAndView showAddCltRcdPage(HttpServletRequest request) {
        String cltAuthId = request.getParameter("cltAuthId");
        try {
            if (StringUtils.isEmpty(cltAuthId)) {
                throw new BaseException("请求参数：委外催收ID不能为空！");
            }
            RskCltAuthVO rskCltAuthVO = rskCltAuthService.selectById(Long.parseLong(cltAuthId));
            if (rskCltAuthVO == null) {
                throw new BaseException("委外催收数据不存在！");
            }

            List<KeyValueVO> cltWayCdList = this.sysDictionaryApiService.getKvList(RiskConstant.CODE_CLT_WAY_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            // 只要1-电话催收  2-上门催收
            cltWayCdList = cltWayCdList.stream().filter(dic -> "1".equals(dic.getKey()) || "3".equals(dic.getKey())).collect(Collectors.toList());

            // 还款意愿（新）
            List<SysDictionaryDTO> repayWishCdList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_PAY_WN_CD);
            List<String> list = Lists.newArrayList();
            for (SysDictionaryDTO dictionaryDTO : repayWishCdList) {
                if (StringUtils.isNotEmpty(dictionaryDTO.getCodeDesc())) {
                    String[] split = dictionaryDTO.getCodeDesc().split(";");
                    Collections.addAll(list, split);
                }
            }
            Map<String, String> wishMap = list.stream().collect(Collectors.toMap(v -> v, v -> v));
            // 欠款原因（新）
            List<KeyValueVO> debtCauseCdList = this.sysDictionaryApiService.getKvList(RiskConstant.CODE_OVD_REASON_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            debtCauseCdList = debtCauseCdList.stream().filter(dic -> wishMap.containsKey(dic.getKey())).collect(Collectors.toList());

            ModelAndView view = new ModelAndView("collection/rskcltauth/addCltRcdPage");
            view.addObject("rskCltAuth", rskCltAuthVO);
            view.addObject("cltWayCdList", JSON.toJSONString(cltWayCdList));
            view.addObject("debtCauseCdList", JSON.toJSONString(debtCauseCdList));
            return view;
        } catch (Exception e) {
            BaseLogUtils.newLogger(cltAuthId + "显示新增催收记录页面失败！操作人：" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

    /**
     * 新增催收记录
     * @param request
     * @return
     */
    @RequestMapping(value = "/addCltRcd.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addCltRcd(HttpServletRequest request, RskCommRecDTO rskCommRecDTO) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        String fileParams = request.getParameter("fileParams");
        try {
            List<SysUlFilesRecVO> fileList = null;
            if (StringUtils.isNotEmpty(fileParams)) {
                fileList = JSON.parseArray(fileParams, SysUlFilesRecVO.class);
            }
            DataResultDTO dataResultDTO = rskCltAuthRecordService.addCltRcd(rskCommRecDTO, fileList);
            if (dataResultDTO == null || dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_NO) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(dataResultDTO.getInfo());
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("委外催收-->新增催收记录业务异常！" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_SUCC + "：" + e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.newLogger("委外催收-->新增催收记录系统异常！" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    /**
     * 到催收记录列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("collection/rskcltauth/rskCltAuthRcdListInfo");
        return view;
    }

    /**
     * 加载委外催收记录列表数据
     * @param request
     * @param qc
     * @return
     */
    @RequestMapping(value = "/initRskCltAuthRcdList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object initRskCltAuthRcdList(HttpServletRequest request, RskCommRecQueryCondition qc) {
        try {
            String currentPage = request.getParameter("page");
            String pageSize = request.getParameter("pagesize");

            Pager page = new Pager();
            if (StringUtils.isNotEmpty(currentPage)) {
                page.setCurrentPage(Integer.parseInt(currentPage));
            }
            if (StringUtils.isNotEmpty(pageSize)) {
                page.setEveryPage(Integer.parseInt(pageSize));
            }

            if(CollectionConstant.THIRD_PARTY_COLLECTION_ORG_CD.equals(CurrentThreadContext.getCurrentOrgCd())){
                //当前用户为第三方机构用户
                qc.setCollectUsrId(CurrentThreadContext.getCurrentUserId());
            }
            page.setCondition(qc);

            page = this.rskCltAuthRecordService.searchCltAuthRecordList(page);

            ListPageVO<RskCommRecDTO> listPage = new ListPageVO<RskCommRecDTO>((List<RskCommRecDTO>) page.getResultList(), page.getTotalCount());
            return listPage;
        } catch (BaseException e) {
            BaseLogUtils.newLogger(CurrentThreadContext.getCurrentUserName() + "查询委外催收记录列表数据业务异常！").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger(CurrentThreadContext.getCurrentUserName() + "查询委外催收记录列表数据系统异常！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }

    /**
     * 查询委外催收记录详情
     * @param request
     * @return
     */
    @RequestMapping(value = "/toRskCltAuthRcdDetailPage.do", method = { RequestMethod.GET})
    public ModelAndView toRskCltAuthRcdDetailPage(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");

            RskCommRecDTO rskCommRecDTO = rskCltAuthRecordService.selectById(Long.parseLong(id));

            RskCltAuthVO rskCltAuthVO = new RskCltAuthVO();
            if (rskCommRecDTO != null && StringUtils.isNotEmpty(rskCommRecDTO.getBizNo())) {
                rskCltAuthVO = rskCltAuthService.selectById(Long.parseLong(rskCommRecDTO.getBizNo()));
            }
            ModelAndView view = new ModelAndView("collection/rskcltauth/cltRcdDetailPage");
            view.addObject("collect", rskCommRecDTO);
            view.addObject("rskCltAuth", rskCltAuthVO);

            return view;
        } catch (BaseException e) {
            BaseLogUtils.newLogger(CurrentThreadContext.getCurrentUserName() + "查询委外催收记录详情数据业务异常！").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger(CurrentThreadContext.getCurrentUserName() + "查询委外催收记录详情数据系统异常！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }

}
